package com.yrd.fssync.core;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.filefilter.HiddenFileFilter;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

public class FileSystemMonitor {
	Context context;
	String id;
	FileAlterationMonitor monitor;
	FileAlterationObserver observer;
	FileSystemListener listener;
	SyncEngineMap syncEngineMap;
	String localBase;
	
	public FileSystemMonitor(Context context,String id,String localBase,FileSystemListener listener) {
		this.context = context;
		this.id = id;
		this.localBase = localBase;
		new File(localBase).mkdirs();
		this.listener = listener;
		this.syncEngineMap = new SyncEngineMap(context);
		this.listener.setSyncEngineMap(syncEngineMap);
//		observer = new FileAlterationObserver(local ,HiddenFileFilter.VISIBLE);
		observer = new FileAlterationObserver(localBase);
		monitor = new FileAlterationMonitor();
		observer.addListener(listener);
		monitor.addObserver(observer);
	}
	
	public FileSystemListener getListener() {
		return listener;
	}

	public String getLocalBase() {
		return localBase;
	}

	public String getId() {
		return id;
	}

	public SyncEngineMap getSyncEngineMap() {
		return syncEngineMap;
	}

	public void post(SyncRequest request){
		post(request,"");
	}

	public void post(SyncRequest request,String target){
		this.syncEngineMap.post(request,target);
	}

	public void start() throws Exception{
		syncEngineMap.start();
		monitor.start();
		Utils.printfln("监听器启动",this);
	}
	
	public void stop() throws Exception{
		monitor.stop();
		syncEngineMap.stop();
		Utils.printfln("监听器关闭",this);
	}
	
	public void addSyncEngine(SyncEngine syncEngine){
		syncEngineMap.add( syncEngine);
	}
	

	@Override
	public String toString() {
		return "FileSystemMonitor [localBase=" + localBase + "]";
	}
	
}
